import { ref } from 'vue';
import { defineStore } from 'pinia';
import { useStorage } from '@vueuse/core';

import { login, getProfile, getRoutes } from '@/apis/auth';

// import { useRequest, useRequestOptions } from '@/utils/use';

export const useAuthStore = defineStore('auth', () => {
  // const data = ref<any>(null);
  // const request = async (dataOpt: API.auth.loginDto) => {
  //   const res = await login(dataOpt);
  //   console.log('login', res);
  //   data.value = res.data;
  // };
  // return { data, request };

  // token
  // const token = ref<string | undefined>();
  const token = useStorage<string | undefined>('token', '');
  // 登录的帐号信息
  const profile = ref<API.auth.ProfileSchema | undefined>();
  // 路由信息
  const routes = ref<API.auth.RouteSchema[] | undefined>();

  // 登录
  const requestLogin = async (dataOpt: API.auth.LoginDto) => {
    return login(dataOpt).then((res) => {
      token.value = res.data.access_token;
      return res;
    });
  };

  // 获取profile
  const requestProfile = async () => {
    return getProfile().then((res) => {
      profile.value = res.data;
      return res;
    });
  };

  // 获取路由权限
  const requestRoutes = async () => {
    return getRoutes().then((res) => {
      routes.value = res.data;
      return res;
    });
  };

  // const request = (dataOpt: API.auth.LoginDto, options?: useRequestOptions) => {
  //   const { result, error } = useRequest<
  //     API.auth.LoginSchema,
  //     API.auth.LoginDto
  //   >(login, dataOpt, options);
  //   watch(result, (val) => {
  //     token.value = val?.data?.access_token;
  //   });
  //   return { result, error };
  // };

  return {
    token,
    profile,
    routes,

    requestLogin,
    requestProfile,
    requestRoutes
  };
});
